<?php

namespace Lib;

final class User {
    use \Lib\Traits\Instance;

    private $_uid   = 0;
    private $_model = null;

    /**
     * 用户登录
     *
     * @param string $mobile
     * @param string $passwd
     * @return boolean
     * @throws \Exception
     */
    public function login($mobile = null, $passwd = null) {
        $request = \Yaf\Dispatcher::getInstance()->getRequest();
        $mobile  = $request->get('mobile', $mobile);
        $passwd  = $request->get('password', $passwd);
        $model   = \Mapper\MemberModel::getInstance()->findByMobile($mobile);

        if(!$model instanceof \MemberModel
            || empty($passwd)
            || \Lib\Passwd::valid($passwd, $model->getPassword()) === false
        ) {
            throw new \Exception('手机号或密码错误', 10104);
        }

        $uid          = $model->getId();
        $this->_uid   = $uid;
        $this->_model = $model;

        \Lib\Token::getInstance()->built(['uid' => $uid]);

        return true;
    }

    /**
     * 校验用户
     *
     * @param int $uid
     * @return boolean
     */
    public function valid($uid) {
        $model  = \Mapper\MemberModel::getInstance()->findById($uid);
        $passed = false;

        if($model instanceof \MemberModel) {
            $passed = true;

            $this->_uid   = $model->getId();
            $this->_model = $model;
        }

        return $passed;
    }

    /**
     * 用户ID
     *
     * @return int
     */
    public function id() {
        $id = $this->_uid;

        if ((int)$id < 65535) {
            \Response::error('Invalid Uid');
            exit;
        }

        return $this->_uid;
    }

    /**
     * 用户数据模型
     *
     * @return \MemberModel
     */
    public function model() {
        return $this->_model;
    }
}
